// pg_copy_guard.cpp
//
// postgres_io_binary.cpp : binary input and output from postgreSQL database
//

#define SEQ_BATCH_SIZE 20000

#include <stdio.h>
#include <string>
#include <iostream>
#define _MY_STL_MACROS 1
#include <stlhelper.h>
#include "pg_db_cursor.h"
#include "pg_copy_guard.h"
using std::string;
using std::ostream;
using std::string;
using std::vector;



//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//		t_pg_copy_guard

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

t_pg_copy_guard::t_pg_copy_guard(t_pg_cursor& pg_db_, const string& table_name_, ostream& CERR_)
	:	pg_db(pg_db_), table_name(table_name_), CERR(CERR_),
		proceeding(false), success(false)
{
	string copy_cmd = "COPY " + table_name + " FROM STDIN";
	if (pg_db.Exec(copy_cmd.c_str()) != PGRES_COPY_IN)
	{
		CERR	<<	"\n"
					"ERROR!! PostgreSQL error.\n\t"
					"Could not COPY data to the postgreSQL table " << table_name << "\n\t"
				<< "[" << copy_cmd << "]\n\t"
				<<		pg_db.ErrorMessage()
				<<	std::endl;
//		pg_db.PutLine ("\\.\n");
//		pg_db.EndCopy();
	}
	else
		proceeding = success = true;
}
void t_pg_copy_guard::cached_write()
{
#ifdef NDEBUG
	if (buf.length() > 32000)
#else
/*	DEBUG
	std::cerr << "\n" << buf;
	if (buf.length() > 10)
*/
#endif
	{
		write();
	}
}

void t_pg_copy_guard::write()
{
#ifndef NDEBUG
/*	DEBUG
	std::cerr << "\n" << buf;
*/
#endif

	if (buf.length())
	{
		pg_db.PutLine (buf.c_str());
		buf.clear();
	}
}
bool t_pg_copy_guard::end_copy()
{
	if (!proceeding)
	{
		CERR 		<<	"\n"
						"ERROR!! PostgreSQL error.\n\t"
						"COPY to the postgreSQL table " << table_name << " failed to start.\n\t";
		return (success = false);
	}
	write();
	proceeding = false;
	pg_db.PutLine ("\\.\n");
	if (pg_db.EndCopy())
	{
		CERR		<<	"\n"
						"ERROR!! PostgreSQL error.\n\t"
						"Could not COPY data to the postgreSQL table " << table_name << "\n\t"
					<<		pg_db.ErrorMessage()
					<<	std::endl;
		return success = false;
	}
	return (success = true);
}


